
local jass = require 'jass.common'

local rect = class('rect')

rect.type = 'rect'
rect.minx = 0
rect.miny = 0
rect.maxx = 0
rect.maxy = 0
rect.j_rects = {}                       --转化jass中的矩形区域
rect.j_points = {}                      --转化jass中的矩形区域为点
rect.map = rect.create(
        jass.GetCameraBoundMinX() - jass.GetCameraMargin(jass.CAMERA_MARGIN_LEFT) + 32,
        jass.GetCameraBoundMinY() - jass.GetCameraMargin(jass.CAMERA_MARGIN_BOTTOM) + 32,
        jass.GetCameraBoundMaxX() + jass.GetCameraMargin(jass.CAMERA_MARGIN_RIGHT) - 32,
        jass.GetCameraBoundMaxY() + jass.GetCameraMargin(jass.CAMERA_MARGIN_TOP) - 32
)
rect.dummy = jass.Rect(0, 0, 0, 0)

function rect:ctor(minx, miny, maxx, maxy)
    if minx then self.minx = minx end
    if miny then self.miny = miny end
    if maxx then self.maxx = maxx end
    if maxy then self.maxy = maxy end
end

--获取4个值
function rect:get()
	return self.minx, self.miny, self.maxx, self.maxy
end

--获取点
function rect:get_point()
	return ac.point((self.minx + self.maxx) / 2, (self.miny + self.maxy) / 2)
end

function rect:contains(point)
	local ret = false
	if not point then
		return ret
	end
	local x, y = point()
	return (x >= self.minx and x <= self.maxx) and (y >= self.miny and y <= self.maxy)
end

function rect:random_pos()
    local x = math.random(self.minx, self.maxx)
    local y = math.random(self.miny, self.maxy)
    return ac.point(x, y)
end

--扩展矩形区域
function rect:__add(dest)
	local minx0, miny0, maxx0, maxy0 = self:get()
	local minx1, miny1, maxx1, maxy1 = table.unpack(dest)
	return rect.create(minx0 + minx1, miny0 + miny1, maxx0 + maxx1, maxy0 + maxy1)
end

	
function rect.j_rect(name)
    if not rect.j_rects[name] then
        local jRect = jass['gg_rct_' .. name]
        rect.j_rects[name] = rect.create(jass.GetRectMinX(jRect), jass.GetRectMinY(jRect), jass.GetRectMaxX(jRect), jass.GetRectMaxY(jRect))
    end
    return rect.j_rects[name]
end

function rect.j_point(name)
    if not rect.j_points[name] then
        local jRect = jass['gg_rct_' .. name]
        rect.j_points[name] = ac.point(jass.GetRectCenterX(jRect), jass.GetRectCenterY(jRect))
    end
    return rect.j_points[name]
end

--获得一个临时的jass区域
function rect.j_temp(rct)
    jass.SetRect(rect.dummy, rct:get())
    return rect.dummy
end

--创建矩形区域
function rect.create(minx, miny, maxx, maxy)
    return rect.new(minx, miny, maxx, maxy)
end

ac.rect = rect

return rect